package com.emperor.aspect;

import com.emperor.anno.AutoFill;
import com.emperor.constant.AutoFillConstant;
import com.emperor.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Pointcut("execution(* com.emperor.mapper.*.*(..)) && @annotation(com.emperor.anno.AutoFill)")
    public void pt() {

    }

    @Before("pt()")
    public void before(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("开始进行公共字段自动填充...");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        log.info("公共字段自动填充完成！");
        OperationType value = annotation.value();
        LocalDateTime now = LocalDateTime.now();
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entry = args[0];
        Class<?> clazz = entry.getClass();

        if (value == OperationType.INSERT) {
            Method setCreateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method updateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);

            // 调用set方法，给公共字段赋值
            setCreateTime.invoke(entry, now);
            updateTime.invoke(entry, now);

        } else if (value == OperationType.UPDATE) {
            Method setUpdateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            // 调用set方法，给公共字段赋值
            setUpdateTime.invoke(entry, now);
        }
    }
}
